package biz.appframe;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import biz.util.ListUtil;
import biz.util.StringUtil;

import com.mysema.query.BooleanBuilder;
import com.rfid.project.exception.CannotDelException;
import com.rfid.project.model.Authority;

@Service
@Transactional
public class MenuService {

	@Autowired
	private MenuDao menuDao;
	
	private QMenu $ = QMenu.menu;

	public MenuDao getMenuDao() {
		return menuDao;
	}

	@Autowired
	public void setMenuDao(MenuDao menuDao) {
		this.menuDao = menuDao;
	}

	public QMenu get$() {
		return $;
	}

	public void set$(QMenu $) {
		this.$ = $;
	}

	public List<Menu> findAll() {
		return this.menuDao.findAll();
	}
	
	public Page<Menu> findAll(String moduleCode, String menuName, int pageNumber, int pageSize) {
		BooleanBuilder condition = new BooleanBuilder();
		if (StringUtil.isNotEmpty(moduleCode)) {
			condition.and($.moduleCode.eq(moduleCode));
		}
		if (StringUtil.isNotEmpty(menuName)) {
			condition.and($.name.contains(menuName));
		}
		
		PageRequest pageRequest = new PageRequest(pageNumber - 1, pageSize);
		return this.menuDao.findAll(condition, pageRequest);
	}
	
	public void save(Menu menu) throws CannotDelException {
		BooleanBuilder condition = new BooleanBuilder();
		boolean flag = true;
		if (null == menu.getId()) {
			condition.and($.name.eq(menu.getName()));
			if(null != this.menuDao.findOne(condition)){
				flag = false;
			}
		} else {
			condition.and($.id.notIn(menu.getId()));
			condition.and($.name.eq(menu.getName()));
			if(this.menuDao.count(condition) > 0){
				flag = false;
			}
		}
		if (flag) {
			this.menuDao.save(menu);
		} else {
			throw new CannotDelException("菜单名称已存在！");
		}
	}

	public void delete(long parseLong) {
		this.menuDao.delete(parseLong);
	}
	
	public List<Menu> findMenuByAuthories(List<Authority> authoritys){
		List<String> managers = new ArrayList<String>();
		for (Authority authority : authoritys) {
			String code = authority.getCode();
			managers.add(code);
		}
		BooleanBuilder condition = new BooleanBuilder();
		condition.and($.code.in(managers));
		return ListUtil.toList(this.menuDao.findAll(condition));
	}

	public Menu findOne(Long id) {
		return this.menuDao.findOne(id);
	}
	
}
